package ext.acae2.statements;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;

import wt.fc.QueryResult;
import wt.log4j.LogR;
import wt.part.Quantity;
import wt.part.WTPart;
import wt.part.WTPartConfigSpec;
import wt.part.WTPartHelper;
import wt.part.WTPartStandardConfigSpec;
import wt.part.WTPartUsageLink;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTRuntimeException;
import wt.vc.views.ViewHelper;
import ext.acae2.statements.bean.ComponentDetailBean;

public class ComponentDetail {

	private static final Logger LOGGER = LogR.getLogger(ComponentDetail.class
			.getName());

	public static void download(WTPart part, OutputStream output)
			throws WTRuntimeException, WTException, IOException {
		LOGGER.debug("> Start download");

		String wthome = (String) WTProperties.getLocalProperties().get(
				"wt.home");

		File templateFile = new File(wthome + File.separator + "codebase"
				+ File.separator + "ext" + File.separator + "acae2"
				+ File.separator + "conf" + File.separator
				+ "ComponentDetail.xls");

		List<ComponentDetailBean> componentDetailList = new ArrayList<ComponentDetailBean>();
		creatComponentDetailBean(part, componentDetailList);
		
		for (ComponentDetailBean componentDetail : componentDetailList) {
			selectAll(componentDetail, componentDetailList, 1L);
        }

		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(templateFile));
		HSSFSheet sheet = workbook.getSheetAt(0);

		HSSFCellStyle seqCst = workbook.createCellStyle();
		seqCst.setBorderTop(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		seqCst.setBorderRight(HSSFCellStyle.BORDER_THIN);
		seqCst.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		
		int rowNum = 4;
		write(componentDetailList, rowNum, sheet, seqCst, part.getContainerName(), part);

		workbook.write(output);
		output.flush();
		output.close();

		LOGGER.debug("> End download");
	}

	private static void creatComponentDetailBean(WTPart part,
			List<ComponentDetailBean> componentDetailList)
			throws RemoteException, WTException {
		
//		if(part.getState().toString().equals("RELEASED")){
			
			if((part.getNumber().length() == 13 && part.getNumber().substring(10,11).equals("M")) || (part.getNumber().length() == 13 && part.getNumber().substring(10,11).equals("G"))){
				
				WTPartStandardConfigSpec standardConfigSpec = WTPartStandardConfigSpec
						.newWTPartStandardConfigSpec(
								ViewHelper.service.getView("Design"), null);
				WTPartConfigSpec configSpec = WTPartConfigSpec
						.newWTPartConfigSpec(standardConfigSpec);
				
				QueryResult childPartsQs = WTPartHelper.service.getUsesWTParts(
						part, configSpec);
				while (childPartsQs.hasMoreElements()) {
					ComponentDetailBean componentDetailBean = new ComponentDetailBean();
					componentDetailBean.setNumber(part.getNumber());
					componentDetailBean.setName(part.getName());

					Object obj[] = null;
					obj = (Object[]) childPartsQs.nextElement();
					if (obj[1] instanceof WTPart) {
						WTPart childPart = (WTPart) obj[1];

						WTPartUsageLink alink = (WTPartUsageLink) obj[0];
						Quantity quantity = alink.getQuantity();

						double singleQuantity = quantity.getAmount();
						String singleStrForParent = String.valueOf(singleQuantity).substring(0,String.valueOf(singleQuantity).lastIndexOf(".")).toString();

						componentDetailBean.setChildPartNumber(childPart.getNumber());
						componentDetailBean.setChildPartName(childPart.getName());
						componentDetailBean.setChildQuantity(singleStrForParent);

						componentDetailList.add(componentDetailBean);
						creatComponentDetailBean(childPart, componentDetailList);
					}
				}
			}
			
//		}
	}

	@SuppressWarnings({ "deprecation", "unchecked" })
	private static void write(List<ComponentDetailBean> componentDetailList,
			int rowNum, HSSFSheet sheet, HSSFCellStyle seqCst, String containerName, WTPart part) {
		
		HSSFRow containerRow = sheet.createRow(1);
		containerRow.createCell(1);
		containerRow.getCell(1).setCellStyle(seqCst);
		containerRow.createCell(7).setCellValue(containerName);
		containerRow.getCell(7).setCellStyle(seqCst);

		String number = "";
		String name = "";
		String quantity = "";
		
		Collections.sort(componentDetailList);
		
		for (ComponentDetailBean componentDetail : componentDetailList) {
			
			if(!componentDetail.getNumber().equals(part.getNumber())){
				HSSFRow row = sheet.createRow(rowNum);
				
				sheet.addMergedRegion(new Region(rowNum,(short)1,rowNum,(short)2)); 

				HSSFRow row1 = sheet.getRow(rowNum-1);
				
				// 件号
	            if(row1.getCell(0).getStringCellValue().equals(componentDetail.getNumber()) || (row1.getCell(0).getStringCellValue() == "" && number.equals(componentDetail.getNumber()))){
	            	row.createCell(0).setCellValue("");
	            }else{
	            	row.createCell(0).setCellValue(componentDetail.getNumber());
	            }
	            
	            // 名称
	            if((row1.getCell(1).getStringCellValue().equals(componentDetail.getName()) && number.equals(componentDetail.getNumber())) || (row1.getCell(1).getStringCellValue() == "" && name.equals(componentDetail.getName()) && number.equals(componentDetail.getNumber()))){
	            	row.createCell(1).setCellValue("");
	            }else{
	            	row.createCell(1).setCellValue(componentDetail.getName());
	            }
	            
	            // 全台数量
	            if((row1.getCell(3).getStringCellValue().equals(componentDetail.getQuantity()) && number.equals(componentDetail.getNumber())) || (row1.getCell(3).getStringCellValue() == "" && quantity.equals(componentDetail.getQuantity()) && number.equals(componentDetail.getNumber()))){
	            	row.createCell(3).setCellValue("");
	            }else{
	            	row.createCell(3).setCellValue(componentDetail.getQuantity());
	            }
	            
	            // 下属零、部、组件
	            // 件号
				row.createCell(4).setCellValue(componentDetail.getChildPartNumber());
				// 名称
				row.createCell(5).setCellValue(componentDetail.getChildPartName());
				// 部组件上数量
				row.createCell(6).setCellValue(componentDetail.getChildQuantity());
				
				number = componentDetail.getNumber();
				name = componentDetail.getName();
				quantity = componentDetail.getQuantity();
				
				rowNum++;
			}
		}
	}
	
	private static void selectAll(ComponentDetailBean componentDetail, List<ComponentDetailBean> componentDetailList, Long l){
		for (ComponentDetailBean componentDetail1 : componentDetailList) {
			if(componentDetail.getNumber().equals(componentDetail1.getChildPartNumber())){
				l = Long.valueOf(componentDetail1.getChildQuantity()) * l;
				selectAll(componentDetail1, componentDetailList, l);
			}
			componentDetail.setQuantity(l+"");
    	}
	}

}
